<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="8" :lg="9" :md="10" :sm="24">
            <a-form-item :label="$t('订单时间')">
              <j-date
                :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                dateFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择开始时间')"
                class="query-group-cust"
                v-model="queryParam.createTime_begin"
              ></j-date>
              <span class="query-group-split-cust"></span>
              <j-date
                :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                dateFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择结束时间')"
                class="query-group-cust"
                v-model="queryParam.createTime_end"
              ></j-date>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="5" :md="6" :sm="24">
            <a-form-item :label="$t('仓库')">
              <a-tree-select
                allowClear
                v-model="queryParam.store"
                style="width: 100%"
                :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="storeList"
                :search-placeholder="$t('请选择')"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="5" :md="6" :sm="24">
            <a-form-item :label="$t('订单状态')">
              <a-select :placeholder="$t('请选择订单状态')" v-model="queryParam.state">
                <a-select-option v-for="(item, index) in stateList" :value="item.value" :key="index">{{
                  item.title
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('出库类型')">
                <a-select v-model="queryParam.outType">
                  <a-select-option value="">{{ $t('全部') }}</a-select-option>
                  <a-select-option v-for="(item, index) in outtypeList" :value="item.id" :key="index">{{
                    item.name
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('操作员')">
                <a-select v-model="queryParam.createBy">
                  <a-select-option v-for="(item, index) in userList" :value="item.id" :key="index">{{
                    item.realname
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('审核人')">
                <a-select v-model="queryParam.audit">
                  <a-select-option v-for="(item, index) in userList" :value="item.id" :key="index">{{
                    item.realname
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24">
              <a-form-item :label="$t('订单号')">
                <a-input :placeholder="$t('请输入订单号')" v-model="queryParam.id"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="7" :md="8" :sm="24" v-if="!tenantid">
              <a-form-item :label="$t('门店')">
                <a-select v-model="queryParam.tenantId">
                  <a-select-option v-for="(item, i) in shops" :key="i" :value="item.value"
                    >{{ item.title }}<span v-if="item.value != ''">（{{ item.value }}）</span></a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="handleReset" icon="reload" style="margin-left: 8px">{{
                $t('重置')
              }}</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? $t('收起') : $t('展开') }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
              <a-button
                type="primary"
                :loading="exloading"
                @click="handleExportXls($t('其他出库单'))"
                style="margin-left: 8px"
                v-has="'BisGoodsOutstockController:export'"
                >{{ $t('导出') }}</a-button
              >
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus" v-has="'BisGoodsOutstockController:add'">{{ $t('新增') }}</a-button>
      <a-button @click="editType" type="primary" v-has="'BisGoodsOutstockTypeController:add'">{{ $t('出库类型管理') }}</a-button>
      <a-button type="primary" icon="import" @click="getImport" v-has="'BisGoodsOutstockController:import'">{{ $t('导入') }}</a-button>
    </div>
    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        class="j-table-force-nowrap"
        :scroll="{ x: true }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无图片') }}</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无文件') }}</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            {{ $t('下载') }}
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)" v-if="record.state != '1'" v-has="'BisGoodsOutstockController:edit'">{{ $t('编辑') }}</a>
          <a-popconfirm :title="$t('您确定要删除该订单吗?')" @confirm="() => handleDelete(record.id)">
            <a v-if="record.state != '1'" style="margin-left: 8px" v-has="'BisGoodsOutstockController:delete'">{{ $t('删除') }}</a>
          </a-popconfirm>
          <a @click="handleDetail(record, 1)" style="margin-left: 8px">{{ $t('详情') }}</a>
          <a v-if="record.state != '1'" @click="handleDetail(record, 2)" style="margin-left: 8px" v-has="'BisGoodsOutstockController:edit'">{{ $t('审核') }}</a>
          <a v-has="'OtherOutOfStore:reverse'" v-if="record.state == '1'" @click="handleDetail(record, 3)" style="margin-left: 8px">{{ $t('反审') }}</a>
        </span>
      </a-table>
    </div>
    <out-store-standby-modal ref="modalForm" @ok="modalFormOk" />
    <edit-out-type-modal ref="typeForm" @ok="modalTypeOk"></edit-out-type-modal>
    <a-modal
      :title="$t('导入')"
      :visible="visible"
      :destroyOnClose="destroyOnClose"
      :confirm-loading="confirmLoading"
      :okText="$t('确定')"
      :cancelText="$t('取消')"
      :width="modal_width"
      :cancel-button-props="cancelbutton"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model ref="ruleForm" :model="ruleForm" :rules="rules" v-bind="layout">
        <a-form-model-item :label="$t('导入模板')">
          <a-button type="primary" icon="download" @click="download($t('出库单导入模板'))">{{
            $t('下载模板')
          }}</a-button>
        </a-form-model-item>
        <a-form-model-item :label="$t('仓库')" prop="store">
          <a-tree-select
            allowClear
            v-model="ruleForm.store"
            style="width: 100%"
            :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="storeListT"
            :search-placeholder="$t('请选择')"
          />
        </a-form-model-item>
        <a-form-model-item :label="$t('出库类型')" prop="outType">
          <div style="display: flex; align-items: center; height: 40px">
            <a-select v-model="ruleForm.outType">
              <a-select-option v-for="(item, index) in outtypeList" :value="item.id" :key="index">{{
                item.name
              }}</a-select-option>
            </a-select>
            <a-button type="primary" @click="addOutType">{{ $t('新增') }}</a-button>
          </div>
        </a-form-model-item>
        <a-form-model-item :label="$t('备注')">
          <a-textarea v-model="ruleForm.comment" rows="4" />
        </a-form-model-item>
        <a-form-model-item :label="$t('导入文件')" prop="name">
          <a-input-group compact>
            <a-input style="width: 80%" v-model="ruleForm.name" disabled></a-input>
            <a-upload
              name="file"
              :showUploadList="false"
              :multiple="false"
              :beforeUpload="beforeUpload"
              :customRequest="selfUpload"
            >
              <a-button style="background-color: #f59a23; color: #ffffff">{{ $t('选择') }}</a-button>
            </a-upload>
          </a-input-group>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import moment from 'moment'
import Vue from 'vue'
import { TENANT_ID } from '@/store/mutation-types'
import { getAction, postAction } from '@/api/manage'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import OutStoreStandbyModal from './modules/OutStoreStandbyModal'
import EditOutTypeModal from './modules/EditOutTypeModal'

export default {
  name: 'OtherOutOfStore',
  mixins: [JeecgListMixin],
  components: {
    OutStoreStandbyModal,
    EditOutTypeModal,
  },
  data() {
    return {
      moment,
      description: '其他出库',
      // 表头
      columns: [
        {
          title: this.$t('订单号'),
          align: 'center',
          dataIndex: 'id',
        },
        {
          title: this.$t('创建时间'),
          align: 'center',
          dataIndex: 'createTime',
        },
        {
          title: this.$t('操作员'),
          align: 'center',
          dataIndex: 'createBy',
        },
        {
          title: this.$t('仓库'),
          align: 'center',
          dataIndex: 'store_dictText',
        },
        {
          title: this.$t('出库类型'),
          align: 'center',
          dataIndex: 'outType_dictText',
        },
        {
          title: this.$t('订单状态'),
          align: 'center',
          dataIndex: 'state_dictText',
          customCell: function (record, text) {
            if (record.state == 0) {
              return {
                style: {
                  color: '#EF2315',
                },
              }
            }
          },
        },
        {
          title: this.$t('备注'),
          align: 'center',
          dataIndex: 'comment',
        },
        {
          title: this.$t('出库时间'),
          align: 'center',
          dataIndex: 'outTime',
        },
        {
          title: this.$t('审核时间'),
          align: 'center',
          dataIndex: 'auditTime',
        },
        {
          title: this.$t('审核人'),
          align: 'center',
          dataIndex: 'audit',
        },
        {
          title: this.$t('操作'),
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/goods/bisGoodsOutstock/list',
        delete: '/goods/bisGoodsOutstock/delete',
        exportXlsUrl: '/goods/bisGoodsOutstock/exportXls',
      },
      dictOptions: {},
      superFieldList: [],
      storeList: [],
      storeListT: [],
      stateList: [],
      userList: [],
      outtypeList: [],
      queryParam: {
        store: '',
        state: '',
        outType: '',
        createBy: '',
        audit: '',
        tenantId: '',
      },
      shops: [],
      tenantid: Vue.ls.get(TENANT_ID), // 导入弹窗
      visible: false,
      destroyOnClose: true,
      confirmLoading: false,
      cancelbutton: { props: { disabled: false } },
      modal_width: '700px',
      ruleForm: {
        filename: '',
        store: '',
        name: '',
      },
      rules: {
        store: [{ required: true, message: this.$t('请选择') }],
        outType: [{ required: true, message: this.$t('请选择') }],
        name: [{ required: true, message: this.$t('请选择导入文件') }],
      },
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 16 },
      },
      file: {},
    }
  },
  created() {
    if (!this.tenantid) {
      initDictOptions('bis_shop,name,code').then((res) => {
        if (res.success) {
          this.shops = res.result
          this.shops.unshift({ value: 0, title: this.$t('总部') })
          this.shops.unshift({ value: '', title: this.$t('全部') })
        }
      })
      this.columns.unshift({
        title: this.$t('所属门店'),
        align: 'left',
        dataIndex: 'tenantId',
        customRender: (t, r) => {
          let str
          if (!t) {
            str = this.$t('总部')
          } else {
            str = r.tenantId_dictText ? t + ' ' + r.tenantId_dictText : t
          }
          return str
        },
      })
    }
  },
  computed: {
    tokenHeader() {
      let head = { 'X-Access-Token': Vue.ls.get('Access-Token') }
      let tenantid = Vue.ls.get(TENANT_ID)
      if (tenantid) {
        head['tenant-id'] = tenantid
      }
      return head
    },
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    addOutType() {
      this.$refs.typeForm.edit(2)
      this.$refs.typeForm.title = this.$t('新增出库类型')
    },
    initDictConfig() {
      this.getStoreList()
      initDictOptions('bis_goods_order.state').then((res) => {
        if (res.success) {
          this.stateList = res.result
          this.stateList.unshift({ value: '', title: this.$t('全部') })
        }
      })
      getAction('/sys/user/list').then((res) => {
        if (res.success) {
          this.userList = res.result.records
          this.userList.forEach((col) => {
            col.id = col.realname
          })
          this.userList.unshift({ id: '', realname: this.$t('全部') })
        }
      })
      this.getOutTypeList()
    },
    getStoreList() {
      let that = this
      let storeList = []
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'id'
      param.order = 'DESC'
      getAction('/goods/bisGoodsStore/rootList', param).then((res) => {
        if (res.success) {
          storeList = res.result.records
          if (storeList.length > 0) {
            storeList.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col)
              }
            })
            that.storeList = that.getDataByResult(storeList)
            that.storeListT = that.getDataByResult(storeList)
            that.storeList.unshift({ key: '', id: '', value: '', title: that.$t('全部') })
          }
        }
      })
    },
    getHasChildStore(store) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = store.id
      getAction('/goods/bisGoodsStore/rootList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col)
              }
            })
            store.children = that.getDataByResult(res.result.records)
            that.storeList = [...that.storeList]
            that.storeListT = [...that.storeListT]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    getDataByResult(result) {
      return result.map((item) => {
        return item
      })
    },
    getOutTypeList(num) {
      getAction('/goods/bisGoodsOutstockType/list', { pageSize: 999 }).then((res) => {
        if (res.success) {
          this.$set(this, 'outtypeList', res.result.records)
          if (num && num == 1) {
            this.ruleForm.outType = this.outtypeList[this.outtypeList.length - 1].id
          }
        }
      })
    },
    handleAdd() {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = this.$t('新增出库单')
      this.$refs.modalForm.disableSubmit = false
    },
    handleDetail(record, state) {
      this.$refs.modalForm.edit(record, state)
      if (state == 1) {
        this.$refs.modalForm.title = this.$t('详情')
      } else if (state == 2) {
        this.$refs.modalForm.title = this.$t('审核')
      } else {
        this.$refs.modalForm.title = this.$t('反审')
      }
      this.$refs.modalForm.disableSubmit = true
    },
    handleReset() {
      this.queryParam = {
        store: '',
        state: '',
        outType: '',
        createBy: '',
        audit: '',
        tenantId: '',
      }
      this.loadData(1)
    },
    editType() {
      this.$refs.typeForm.edit(1, this.tenantid)
      this.$refs.typeForm.title = this.$t('出库类型管理')
    },
    modalFormOk() {
      this.loadData(this.ipagination.current)
      this.getOutTypeList()
    },
    modalTypeOk(arg) {
      this.loadData(1)
      if (arg == 2) {
        this.getOutTypeList(1)
      }
      if (arg == 3) {
        this.getOutTypeList()
      }
    },
    /**
     * 导入弹窗
     */
    getImport() {
      this.visible = true
      this.ruleForm = {
        filename: '',
        name: '',
      }
    },
    /**
     * 下载模板
     */
    download(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = this.$t('导出文件')
      }
      let url = window._CONFIG['domianURL'] + 'importTemplate/出库单导入模板.xls'
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.download = fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) //下载完成移除元素
      window.URL.revokeObjectURL(url) //释放掉blob对象
      return
    },
    /* 导入 */
    handleImportExcel1(info) {
      if (info.file.status !== 'uploading') {
        this.ruleForm.name = info.file.name
        this.ruleForm.filename = info.file.response.message
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          if (info.file.response.code === 201) {
            let {
              message,
              result: { msg, fileUrl, fileName },
            } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
          } else {
            this.$message.success(info.file.response.message || `${info.file.name} ` + this.$t('文件上传成功'))
          }
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(this.$t('文件上传失败') + ': '` ${info.file.msg} `)
      }
    },
    /**
     * 弹窗确定
     */
    handleOk(e) {
      let that = this
      that.$refs.ruleForm.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          that.cancelbutton = { props: { disabled: true } }
          const formData = new FormData()
          formData.append('file', that.file)
          formData.append('store', that.ruleForm.store)
          formData.append('state', '0')
          formData.append('outType', that.ruleForm.outType)
          if (that.ruleForm.comment) {
            formData.append('comment', that.ruleForm.comment)
          }
          postAction('/goods/bisGoodsOutstock/importExcel', formData).then((res) => {
            if (res.success) {
              setTimeout(() => {
                ;(that.cancelbutton = { props: { disabled: false } }), (that.confirmLoading = false)
                that.visible = false
                that.$message.success(res.message)
                that.loadData(1)
              }, 1000)
            } else {
              that.$message.error(res.message)
              setTimeout(() => {
                ;(that.cancelbutton = { props: { disabled: false } }), (that.confirmLoading = false)
              }, 1000)
            }
          })
        } /*  else {
          that.$message.warning(that.$t('请检查输入项'))
          return false
        } */
      })
    },
    /**
     * 弹窗取消
     */
    handleCancel(e) {
      this.visible = false
      this.$refs.ruleForm.resetFields()
    },
    beforeUpload(file) {
      let that = this
      that.file = file
      that.ruleForm.name = file.name
    },
    selfUpload() {},
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>